# -*- encoding : utf-8 -*-
class Default::UserController < ApplicationController
  # specific layout
  layout 'default/application'
  
  # login
  def login
    
  end
  def login_attempt
    authorized_user = User.authenticate(params[:username_or_email], params[:login_password])
    
    if(authorized_user)
      session[:user_id] = authorized_user.id
      redirect_to(:controller => 'default/book', :action => 'index')
    else
      flash[:notice] = "Username or Password is incorrect!"
      render 'login'
    end
  end
  
  def logout
    session[:user_id] = nil
    redirect_to :controller => 'default/book', :action => 'index'
  end
  
  def profile
    @current_user = User.find(session[:user_id])
  end
  
  def setting
    user = User.find(session[:user_id])
    case(params[:attr])
      when 'fullname' then
        user.update_attribute('fullname', params[:fullname])
        flash[:notice] = 'You updated Full Name successfully!'
      when 'email' then
        user.update_attribute('email', params[:email])
        flash[:notice] = 'You updated Email successfully!'
      when 'phone' then
        user.update_attribute('phone', params[:phone])
        flash[:notice] = 'You updated Phone Number successfully!'
      when 'password' then
        cur_passw_encrypted = BCrypt::Engine.hash_secret(params[:current_passw], user.salt)
        if(cur_passw_encrypted == user.password)
            if(params['new_passw'] == params['new_passw_confirm'])
              new_passw_encrypted = BCrypt::Engine.hash_secret(params[:new_passw], user.salt)
              user.update_attribute('password', new_passw_encrypted)
              UserMailer.change_passw(user).deliver
              flash[:notice] = 'You updated Password successfully!'
            else
              flash[:notice] = 'New password and new password confirmation is not match'
            end
        else
          flash[:notice] = 'Current password is incorrect!'
        end
    end
    
    redirect_to :controller => 'default/user', :action => 'profile'
  end
  
  def forgot_passw
    if(params[:username_or_email])
      user = User.find_by_username(params[:username_or_email])
      if(!user)
        user = User.find_by_email(params[:username_or_email])
      end

      if(user)
        new_passw = rand(10000000..99999999)
        encrypted_passw = BCrypt::Engine.hash_secret(new_passw, user.salt)
        user.update_attribute('password', encrypted_passw)
        UserMailer.reset_passw(user, new_passw).deliver
        flash[:notice] = "Resetting password successfully! A new password is sent to your email!"
      else
        flash[:notice] = "Username or Email is not exist!"
      end
    end
  end
  
  def test
    user = User.find(13)
    user.password = '123456'
    user.update_attribute('password', user.password)
    
    render 'login'
  end
end
